using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class CardsPanel : MonoBehaviour
{
    public int row = 4;
    public int col = 4;
    public float aspectRatio = 1; // 卡牌图片宽高比
    public float spacing = 16;
    public GameObject cardPrefab;
    
    private float panelWidth;
    private float cardWidth;
    private float cardHeight;
    private List<Card> cards = new List<Card>();
    private int totalPairs; // 总对数
    private int foundPairs; // 已配对数
    private int attempts; // 尝试翻牌次数
    private List<Card> penddings = new List<Card>(); // 待匹配列表
    private GameManager gm;
    
    void Start()
    {
        gm = GameManager.Instance;
        
        // 获取面板宽高
        RectTransform containerRect = GetComponent<RectTransform>();
        panelWidth = containerRect.rect.width;
    }
    
    void ShuffleList(List<int> list)
    {
        for (int i = 0; i < list.Count - 1; i++)
        {
            int temp = list[i];
            int rand = Random.Range(i, list.Count);
            list[i] = list[rand];
            list[rand] = temp;
        }
    }

    void CreateCards(List<int> list)
    {
        foreach (int idx in list)
        {
            GameObject cardObj = Instantiate(cardPrefab, transform);
            Card card = cardObj.GetComponent<Card>();
            card.Init(idx, cardWidth, cardHeight, gm.cards[idx]);
        }
    }

    public void Init()
    {
        // 清空面板
        foreach (Transform child in transform)
        {
            Destroy(child.gameObject);
        }
        // 清空卡片
        cards.Clear();
        // 计算开拍宽高
        cardWidth = (panelWidth - (col + 1) * spacing) / col;
        cardHeight = cardWidth / aspectRatio;
        // 面板布局属性
        GridLayoutGroup gridLayoutGroup = GetComponent<GridLayoutGroup>();
        gridLayoutGroup.constraintCount = col * row;
        gridLayoutGroup.cellSize = new Vector2(cardWidth, cardHeight);
        gridLayoutGroup.spacing = new Vector2(spacing, spacing);
        // 生成卡牌
        List<int> cardValues = new List<int>();
        totalPairs = row * col / 2;
        foundPairs = 0;
        attempts = 0;
        for (int i = 0; i < totalPairs; i++)
        {
            cardValues.Add(i);
            cardValues.Add(i);
        }
        // 洗牌
        ShuffleList(cardValues);
        // 实例化卡牌
        CreateCards(cardValues);
    }

    public void MatchCard(Card card)
    {
        attempts += 1;
        if (penddings.Count >= 2)
        {
            penddings[0].Flip();
            penddings.RemoveAt(0);
        }
        
        penddings.Add(card);
        StartCoroutine(FlipCardToBack(card));
        
        if (penddings.Count == 2 && penddings[0].GetValue() == card.GetValue())
        {
            penddings[0].SetIsMatched();
            card.SetIsMatched();
            penddings.Clear();
            foundPairs += 1;
            gm.UpdateScore(gm.score + 10);
            if (foundPairs >= totalPairs)
            {
                gm.GameOver();
            }
        }
    }

    IEnumerator FlipCardToBack(Card card)
    {
        yield return new WaitForSeconds(1.5f);
        if (penddings.Contains(card))
        {
            card.Flip();
            penddings.Remove(card);
        }
    }
}
